<?php

class UserServiceController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
		public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','StaffDistribution','Reback3'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete','Distribution','Reback','Reback2','AgentDistribution'),
				'expression'=>array($this,'isTopUser'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new UserService;
		if(isset($_POST['UserService']))
		{
			$model->attributes=$_POST['UserService'];
			$model->create_user=yii::app()->user->id;
			$model->access_id=$model->user_id;
			$model->equipment_number = $model->getOneEquipmentName($model->equipment_id);
			if($model->save()){
				$equipment_sql="update zy_equipment set updater='".$model->user_id."' where equipment_id =".$model->equipment_id;
				$equipment_result=yii::app()->db->createCommand($equipment_sql);
				$equipment_result->execute();
				//当service_id是iptv时,直接向loginlist写入一条空数据.
				if($model->service_id==14){
					$loginlist=new LoginList;
					$loginlist->user_service_id=$model->attributes['user_service_id'];
					$loginlist->save();
				}
				if($model->service_id==8){	//如果service 等于 智能路由则更新或者新建一条数据到zy_updatestatus表
					$crate_time=date("Y-m-d H:i:s");
					$crate_user=yii::app()->user->name;
					$sql_query="select * from zy_updatestatus where user_id='".$model->user_id."'";
					$rs = yii::app()->db->createCommand($sql_query)->queryAll();
					if(empty($rs[0]['user_id'])){
						$sql="INSERT INTO `zy_updatestatus`(`user_id`,`routeupdate`,`crate_time`,`crate_user`) VALUES ('$model->user_id',1,'$crate_time','$crate_user')";
					}else{
						$sql="UPDATE `zy_updatestatus` SET `routeupdate` = '1',`update_time` = '$crate_time',`update_user` = '$crate_user' WHERE `user_id` = '$model->user_id'";
					}
					yii::app()->db->createCommand($sql)->execute();
				}
				$this->redirect(array('loginList/create','user_service_id'=>$model->user_service_id));
			}
		}
		
		$this->render('create',array(
			'model'=>$model,
		));
	}
	public function actionDistribution()
	{
		$model=new UserService;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['access_id']))
		{
			$creater= $_POST['creater'];
			$access_id = $_POST['access_id'];
			$equipment = $_POST['equipment'];
			$service_id=12;
			$isreback=1;// 从admin->sale isreback不变 
			$isused=0;//表示已分配后设备在销售员手里
			$city=$_POST['city'];
			for($i=0;$i<count($equipment);$i++) {
				$equipment_id = $equipment[$i];
				$userservice=UserService::model()->find('equipment_id='.$equipment_id.' AND isreback>0 AND access_id=0 AND isused=1');
				if($userservice->isreback!=2){
					$rs=Equipment::model()->findByPk($equipment_id);
					$equipment_number=$rs->equipment_number;
					$sql="Insert into zy_user_service (create_user,access_id,equipment_id,service_id,isreback,isused,equipment_number) values (:create_user,:access_id,:equipment_id,:service_id,:isreback,:isused,:equipment_number)";
					$result = yii::app()->db->createCommand($sql);
					$result->bindParam(":create_user",$creater);
					$result->bindParam(":access_id",$access_id);
					$result->bindParam(":equipment_id",$equipment_id);
					$result->bindParam(":service_id",$service_id);
					$result->bindParam(":isreback",$isreback);
					$result->bindParam(":isused",$isused);
					$result->bindParam(":equipment_number",$equipment_number);
					$result->execute();
					// is_used=1 表示设备不在admin里面
					$equipment_sql="update zy_equipment set is_used = 1,city= '".$city."',updater='".$access_id."' where equipment_id =".$equipment_id;
					$equipment_result=yii::app()->db->createCommand($equipment_sql);
					$equipment_result->execute();
					
					$phone_number=$rs->telephone_number;
					$expiredate=date('Y-m-d H:i:s',strtotime("+24 hours"));
					setExpireDateByPhoneNumber($phone_number,$expiredate);
				}else{
					$userservice->access_id=$access_id;
					$userservice->isused=0;
					$userservice->update();
					$rs=Equipment::model()->findByPk($equipment_id);
					$rs->is_used=1;
					$rs->update();
				}
			}
			$this->redirect(array('user/admin','level'=>6));
		}
		$this->render('Distribution',array(
				'model'=>$model,
		));
	}
	// 代理人设备分配 
	public function actionAgentDistribution(){
		$model=new UserService;
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['access_id']))
		{
			UserService::model()->AgentDistribution();
			$this->redirect(array('user/admin','level'=>yii::app()->user->level3()));
		}
		$this->render('AgentDistribution',array(
				'model'=>$model,
		));
	}
	public function actionStaffDistribution(){
		$model=new UserService;
	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['access_id']))
		{
			UserService::model()->StaffDistribution();
			$this->redirect(array('user/admin','level'=>yii::app()->user->level3()));
		}
		$this->render('StaffDistribution',array(
				'model'=>$model,
		));
	}
	public function actionReback()
	{
		$model=new UserService;	
		if(isset($_POST['access_id']))
		{
			$equipment = $_POST['equipment'];			
			for($i=0;$i<count($equipment);$i++) {
				$equipment_id = $equipment[$i];
				$userservice=UserService::model()->find('equipment_id='.$equipment_id.' AND isreback>0 AND access_id='.$_POST['access_id'].' AND isused=0');
				$rs=Equipment::model()->find('equipment_id='.$equipment_id);
				if($userservice->isreback!=2){
					// isused = 1 表示不在销售员手里
					$userservice_sql="update zy_user_service set isused = 1,access_id=0 where equipment_id =".$equipment_id." and access_id=".$_POST['access_id'];
					$userservice_result=yii::app()->db->createCommand($userservice_sql);
					$userservice_result->execute();
					$equipment_sql="update zy_equipment set is_used = 0,updater=0,city='' where equipment_id =".$equipment_id;
					$equipment_result=yii::app()->db->createCommand($equipment_sql);
					$equipment_result->execute();
					$phone_number=$rs->telephone_number;
					$expiredate=date('Y-m-d H:i:s',strtotime("-24 hours"));
					setExpireDateByPhoneNumber($phone_number,$expiredate);
				}else{
					$userservice->access_id=0;
					$userservice->isused=1;
					$userservice->update();
					$rs=Equipment::model()->findByPk($equipment_id);
					$rs->is_used=0;
					$rs->update();
				}
		}
			$this->redirect(array('user/admin','level'=>6));
		}
		$this->render('reback',array(
				'model'=>$model,
		));
	}
	public function actionReback2(){
		$model=new UserService;
		if(isset($_POST['access_id']))
		{
			$equipment = $_POST['equipment'];
			for($i=0;$i<count($equipment);$i++) {
				$equipment_id = $equipment[$i];
				$userservice=UserService::model()->find('equipment_id='.$equipment_id.' AND isreback>0 AND access_id='.$_POST['access_id'].' AND isused=0');
				if($userservice->isreback!=2){
					// isused = 1 表示不在销售员手里
					$userservice_sql="update zy_user_service set isused = 1,access_id=0 where equipment_id =".$equipment_id." and access_id=".$_POST['access_id'];
					$userservice_result=yii::app()->db->createCommand($userservice_sql);
					$userservice_result->execute();
					$equipment_sql="update zy_equipment set is_used = 0,updater=0,city='' where equipment_id =".$equipment_id;
					$equipment_result=yii::app()->db->createCommand($equipment_sql);
					$equipment_result->execute();
				}else{
					$userservice->access_id=0;
					$userservice->isused=1;
					$userservice->update();
					$rs=Equipment::model()->findByPk($equipment_id);
					$rs->is_used=0;
					$rs->update();
				}
			}
			$this->redirect(array('user/admin','level'=>yii::app()->user->level3()));
		}
		$this->render('reback2',array(
				'model'=>$model,
		));
	}
	// 职工代理返还给公司代理人
	public function actionReback3(){
		$model=new UserService;
		if(isset($_POST['access_id']))
		{
			$equipment = $_POST['equipment'];
			for($i=0;$i<count($equipment);$i++) {
				$equipment_id = $equipment[$i];
				$userservice=UserService::model()->find('equipment_id='.$equipment_id.' AND isreback>0 AND access_id='.$_POST['access_id'].' AND isused=0');
				if($userservice->isreback!=2){
					// isused = 1 表示不在销售员手里
					$userservice_sql="update zy_user_service set isused = 1,access_id=0 where equipment_id =".$equipment_id." and access_id=".$_POST['access_id'];
					$userservice_result=yii::app()->db->createCommand($userservice_sql);
					$userservice_result->execute();
					$equipment_sql="update zy_equipment set is_used = 1,istop=0,updater=".yii::app()->user->id." where equipment_id =".$equipment_id;
					$equipment_result=yii::app()->db->createCommand($equipment_sql);
					$equipment_result->execute();
				}else{
					$userservice->access_id=0;
					$userservice->isused=1;
					$userservice->update();
					$rs=Equipment::model()->findByPk($equipment_id);
					$rs->is_used=0;
					$rs->update();
				}
			}
			$this->redirect(array('user/admin','level'=>yii::app()->user->level3()));
		}
		$this->render('reback3',array(
				'model'=>$model,
		));
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['UserService']))
		{
			$model->attributes=$_POST['UserService'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('UserService');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new UserService('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['UserService']))
			$model->attributes=$_GET['UserService'];
		$id = yii::app()->user->id;
		$level = yii::app()->user->level;
		$access_id=yii::app()->request->getParam(access_id);
		if($level==1){
			$sql="SELECT user_id FROM zy_user";
		}elseif($level==2){
			$sql ="select user_id from zy_user where user_id =".$id." or parentId = ".$id;
		}else{
			$sql = "select user_id from zy_user where user_id =".$id;
		}
		
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql);
		$results = $command->queryAll();
		for($i=0;$i<count($results);$i++){
			$result[$i]=$results[$i]['user_id'];
		}
		$this->render('admin',array(
				'model'=>$model,
				'results'=>$result
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=UserService::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-service-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	protected function isTopUser()
	
	{
	
		$level = Yii::app()->user->level();
	
		return ($level==2 || $level==1 || $level==6);
	
	}
	protected function isAdmin()
	
	{
	
		$level = Yii::app()->user->level();
	
		return ($level==1);
	
	}
}
